<?php

namespace app\model;

use support\Db;
use support\Log;
use support\Model;
use support\Redis;

class Package extends Model
{
    protected $table = 'packages';
    protected $connection = 'mysql_admin';
    protected $primaryKey = 'id';
    public $timestamps = false;
    const CONFIG_FILE_DOMAIN = 'http://download.tapplus.com/';
    const CONFIG_KEY = '_package_config_';
    const CONFIG_KEY_ALL = '_package_config_all_';
    const FCM_CHANNEL_NAME = 'FCM';
    const APN_CHANNEL_NAME = 'APNs';
    const HUAWEI_CHANNEL_NAME = 'HUAWEI';
    const MAPPING =[
        16 => 15,
    ];

    public static function getPackageConfig($type='all'){
        $ids = null;
        if($type!='all'){
            $ids = Redis::zRangeByScore(self::CONFIG_KEY_ALL,$type,$type);
        }

        $list = self::updateGetConfig($ids);
        $mappingList = self::MAPPING;
        foreach ($mappingList as $id =>$configId){
            isset($list[$configId]) && $list[$id] = $list[$configId];
        }
        return $list;
    }

    public static function getPackagePushConfig($package_id){
        $package_configList = Package::getPackageConfig();
        $configuration = $package_configList[$package_id]['configuration'] ?? '';
        $configuration = json_decode($configuration,true) ?: [];
        return $configuration;
    }

    public static function getHuaWeiConfig($package_id){
        $package_configList = self::getPackageConfig(1);
        $config = $package_configList[$package_id] ?? [];
        $config['package_name'] = 'test';
        $config['app_id'] = '106764689';
        $config['app_secret'] = '16231eaa94ff5e7451de2827e799214b8f2c399e271d355fe626f47be17d61bf';
        return $config;
    }


    public static function updateGetConfig($package_id=null,$refresh=false){
        if($package_id){
            !is_array($package_id) && $package_id = [$package_id];
        }
        $configs = [];
        if(!$refresh){
            if($package_id===null) {
                $package_id = Redis::zRange(self::CONFIG_KEY_ALL,0,-1);
            }
            foreach ($package_id as $id) {
                $config = Redis::hgetall(self::config_key($id));
                $configs[$id] = $config;
            }
            return $configs;
        }
        $build = $build = Db::connection('mysql_admin')->table('packages');;
        $package_id && $build = $build->wherein('id',$package_id);
        $list = $build->select()->orderBy('id','desc')->get();

        foreach ($list as $item){

            $item = object2array($item);
            $config = [];
            $id = $item['id'];
            $plugin_params = json_decode($item['plugin_params'],true);
            $name = $item['name'];
            $type = $item['plugin_type'];

            $params = self::getPackagePlugin($plugin_params,$type);
            $huawei = $fcm = [];
            if($type==1){
                $fcm = $params[0];
                $huawei = $params[1];
                if(empty($fcm) && empty($huawei)) continue;
            }else{
                if(empty($params)) continue;

            }
            //dump($id,$params);
            $config['type'] = $type;
            $config['cate_id'] = $item['cate_id'];
            $config['game_id'] = $item['game_id'];
            $config['package_id'] = $id;
            $config['package_name'] = $name;
            $config['mark'] = $item['mark'] ?: '';

            if($type==1){
                //if(empty($fcm)) continue;
                if($fcm){
                    $error = [];
                    $config = array_merge($config,$fcm);
                    $project_file = $config['project_file'] ?? '';
                    $url = self::CONFIG_FILE_DOMAIN.urlencode($project_file);
                    try{
                        $fileContent = file_get_contents($url);
                    }catch (\Throwable $exception){
                        $fileContent = '';
                        $error[] = $exception->getMessage();
                    }
                    $fileConfig = $fileContent;
                    if(empty($project_file) || !$fileContent || empty($fileConfig)){
                        Log::channel('system')->warning("package_id:{$id} no project_file({$project_file}) in domain {$url}:error:".var_export($error,true));
                        continue;
                    }
                    $config['configuration'] = $fileConfig;
                }
                if($huawei){
                    $client_id = $huawei['client_id'] ?? '';
                    $client_secret = $huawei['client_secret'] ?? '';
                    if(!$client_id || !$client_secret){
                        Log::channel('system')->warning("package_id:{$id} no client_id:{$client_id},client_secret:{$client_secret}");
                        //continue;
                    }
                    $config[self::HUAWEI_CHANNEL_NAME] = json_encode(compact('client_id','client_secret'));
                }
                $configs[$id] = $config;
            }elseif($type==2){
                $config = array_merge($config,$params);
                $private_key_file = $config['private_key_file'] ?? '';
                $url = self::CONFIG_FILE_DOMAIN.urlencode($private_key_file);
                try{
                    $fileContent = file_get_contents($url);
                }catch (\Throwable $exception){
                    $fileContent = '';
                }


                if(empty($private_key_file) || !$fileContent){
                    Log::channel('system')->warning("package_id:{$id} no project_file({$private_key_file}) in domain {$url}");
                    continue;
                }
                $config['private_key'] = $fileContent;
                $configs[$id] = $config;
            }


        }
        self::saveConfig($configs);
        return $configs;
    }

    protected static function saveConfig($configs){
        foreach ($configs as $id => $config){
            Redis::hmset(self::config_key($id),$config);
            Redis::zadd(self::CONFIG_KEY_ALL,$config['type'],$id);
        }
    }

    protected static function config_key($id){
        return self::CONFIG_KEY.$id;
    }

    /**
     * 获取包的推送相关插件参数
     * @param $plugin_params
     * @param $type
     * @return array
     */
    protected static function getPackagePlugin($plugin_params, $type)
    {
        is_string($plugin_params) && $plugin_params = json_decode($plugin_params,true);
        if($type==1){
            $params = [];
            $params[] = $plugin_params[self::FCM_CHANNEL_NAME] ?? [];
            $params[] = $plugin_params[self::HUAWEI_CHANNEL_NAME] ?? [];
            return $params;
        }
        if($type==2){
            return $plugin_params[self::APN_CHANNEL_NAME] ?? [];
        }
    }

}
